package com.hanhai.material.config.websocket;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.hanhai.material.common.result.Result;
import com.hanhai.material.device.entity.SysMaterialRecord;
import com.hanhai.material.device.model.WebSocketData;
import com.hanhai.material.device.service.SysMaterialRecordService;
import com.hanhai.material.utils.redis.RedisUtil;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.log4j.Log4j2;
import org.apache.catalina.AccessLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import static com.hanhai.material.device.entity.table.SysMaterialRecordTableDef.SYS_MATERIAL_RECORD;
import static com.hanhai.material.utils.TimeUtils.fromDateToString;


/**
 * @author websocket服务
 */
@ServerEndpoint(value = "/websocket/{id}",encoders = ServerEncoder.class)
@Component
@Log4j2
public class WebSocketServer {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    SysMaterialRecordService sysMaterialRecordService;

    /**
     * 记录当前在线连接数
     */
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        //websocket 使用service 层
        ApplicationContext act = ApplicationContextRegister.getApplicationContext();
        session.setMaxIdleTimeout(24*60*1000);
        sessionMap.putIfAbsent(id, session);
        this.redisUtil=act.getBean(RedisUtil.class);
        this.sysMaterialRecordService=act.getBean(SysMaterialRecordService.class);
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.where(SYS_MATERIAL_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",new Date())));
        queryWrapper.orderBy(SYS_MATERIAL_RECORD.WORK_PLAN_ID,true);
        List<SysMaterialRecord> sysMaterialRecordList=this.sysMaterialRecordService.list(queryWrapper);
        Object object=this.redisUtil.get("websocket");
        WebSocketData webSocketData= com.alibaba.fastjson.JSONObject.parseObject(com.alibaba.fastjson.JSONObject.toJSONString(object), WebSocketData.class);
        webSocketData.setAllRecordList(sysMaterialRecordList);
        if(object!=null){
            sendData(object);
        }
        log.warn("有新用户加入，id={}, 当前在线人数为：{}", id, sessionMap.size());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("id") String id) {
        sessionMap.remove(id);
        log.warn("有一连接关闭，移除id={}的用户session, 当前在线人数为：{}", id, sessionMap.size());
    }

    /**
     * 收到客户端消息后调用的方法
     * 后台收到客户端发送过来的消息
     * onMessage 是一个消息的中转站
     * 接受 浏览器端 socket.send 发送过来的 json数据
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam("id") String id) {
        //websocket 使用service 层
        ApplicationContext act = ApplicationContextRegister.getApplicationContext();

        log.warn("服务端收到用户id={}的消息:{}", id, message);
        JSONObject obj = JSONUtil.parseObj(message);
        String key = obj.getStr("ping");
        Session toSession = sessionMap.get(id);
        log.error("Session:{}",toSession);
        if (toSession != null) {
            // 服务器端 再把消息组装一下，组装后的消息包含发送人和发送的文本内容
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("pong",true);
            sendMessage(jsonObject.toString(), toSession);
            this.sysMaterialRecordService=act.getBean(SysMaterialRecordService.class);
            QueryWrapper queryWrapper=QueryWrapper.create();
            queryWrapper.where(SYS_MATERIAL_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",new Date())));
            queryWrapper.orderBy(SYS_MATERIAL_RECORD.WORK_PLAN_ID,true);
            List<SysMaterialRecord> sysMaterialRecordList=this.sysMaterialRecordService.list(queryWrapper);
            log.error("Matericla:ss:{}",sysMaterialRecordList);
            Object object=this.redisUtil.get("websocket");
            WebSocketData webSocketData= com.alibaba.fastjson.JSONObject.parseObject(com.alibaba.fastjson.JSONObject.toJSONString(object), WebSocketData.class);
            webSocketData.setAllRecordList(sysMaterialRecordList);
            this.redisUtil.set("websocket",webSocketData);
            log.error("Matericla:ss:{}",webSocketData);
            if(object!=null){
                sendData(object);
            }

        }
    }

    @OnError
    public void onError(Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 服务端发送消息给客户端
     */
    public static void sendMessage(String message, Session toSession) {
        try {
            log.warn("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }

    /**
     * 服务端发送消息给所有客户端
     */
    public static void sendAllMessage(String message) {
        try {
            for (Session session : sessionMap.values()) {
                log.warn("服务端给客户端[{}]发送消息{}", session.getId(), message);
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }

    public static void sendData(Object result){
        try {
            for (Session session : sessionMap.values()) {
                log.warn("服务端给客户端[{}]发送消息{}", session.getId(), result.toString());
//                session.getBasicRemote().sendText(JSON.toJSONString(result));
                session.getBasicRemote().sendText(JSON.toJSONString(result));
            }
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }
}